use std::sync::Arc;
use std::time::Duration;

use futures::SinkExt;
use futures::stream::SplitSink;
use tokio::net::TcpStream;
use tokio::sync::Mutex;
use tokio::time;
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream};
use tokio_tungstenite::tungstenite::{Message, Utf8Bytes};

use crate::auth::get_app_access_token;
use crate::auth::model::{Auth, Login};
use crate::model::WebSocketMessage;
use crate::qq::{auth, heart_beat};

pub async fn handle(message: WebSocketMessage, arc_writer: &Arc<Mutex<SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>>>) {
    // QQBot登录
    let login = Arc::clone(&arc_writer);
    auth::login(login).await;
    println!("QQBot登录成功！");
    time::sleep(Duration::from_secs(1)).await;
    // 启动心跳！
    let ack = Arc::clone(arc_writer);
    tokio::spawn(heart_beat::keep(ack, message.d.clone().unwrap().heartbeat_interval));
    return;
}

pub async fn login(arc_lock: Arc<Mutex<SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>>>) {
    let token = get_app_access_token().await;
    let login = Login::<Auth>::new(Some(token));
    let send = Message::Text(Utf8Bytes::from(serde_json::to_string(&login).ok().unwrap()));
    let mut write = arc_lock.lock().await;
    write.send(send).await.expect("发送失败！");
}

// pub async fn reconnect(reconnect: Arc<Mutex<SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>>>, session_id: Option<String>, seq: Option<i32>) {
//     let token = get_app_access_token().await;
//     let login = Login::<Reconnect>::new(token, session_id, seq);
//     let send = Message::Text(serde_json::to_string(&login).expect("转换失败！"));
//     let mut write = reconnect.lock().await;
//     write.send(send).await.expect("发送失败！");
// }